<script>
import ButtonList from '@/components/ButtonList'
import TableButtonList from '@/components/TableButtonList'
import WrapTable from '@/components/WrapTable'
import store from './store'
import Form from '@/components/Form'
import SearchForm from '@/components/SearchForm'
import { commonMixin } from '@/mixins/common'
import { funType } from '@/utils/store/jsonCode.js'
import { parseTime } from '@/utils/index.js'
import ContainerList from '@/components/ContainerList'
import emitter from '@/mixins/emitter'
import AjaxStore from '@/utils/store/proxyAjax'

export default {
  name: 'roleFenpei',
  mixins: [store, emitter, commonMixin],
  components: {
    ButtonList,
    ContainerList
  },
  inject: ['Dialog', 'user'],
  data() {
    return {
      limitNum: 5,
      selectedList: [],
      containerList: [],
      currentUserKey: '当前人员',
      currentUserName: '',
      idKey: 'roleId',
      store: new AjaxStore({
        url: '/v1/sys/role/query'
      }),
      spanLeftVal: 12,
      spanRightVal: 12,
      columns: [
        {
          prop: 'roleName',
          label: '角色名称',
          sortable: true,
          'header-align': 'center',
          'show-overflow-tooltip': true
        },
        {
          prop: 'remark',
          label: '描述',
          sortable: true,
          'header-align': 'center',
          'show-overflow-tooltip': true
        }
      ]
    }
  },
  computed: {
    data() {
      return this.store.data
    },
    total() {
      return this.store.total
    }
  },
  watch: {
    'Dialog.visible': {
      immediate: true,
      handler(val) {
        val && this._getInfo()
      }
    },
    data: {
      // immediate: true,
      handler(val) {
        val && this.handleCheckCheckbox()
      }
    }
  },
  methods: {
    getData({ page, limit }) {
      this.store.read({ start: page, limit: limit })
    },
    _getInfo() {
      this.getData({ page: 1, limit: 5 })
      this.currentUserName = this.user.userName
      this.user
        .getHavedRole({ userId: this.user.userId })
        .then(res => {
          if (res.success) {
            this.user.roleFenpeiLoading = false
            this.containerList = res.data
            this.handleCheckCheckbox()
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
            this.dialogType = ''
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    handleSelect(selection, row) {
      let flag = false
      for (let i = 0; i < selection.length; ++i) {
        if (row.roleId === selection[i].roleId) {
          flag = true
          break
        }
      }
      if (!flag) {
        for (let i = 0; i < this.containerList.length; ++i) {
          if (row.roleId === this.containerList[i].roleId) {
            this.containerList.splice(i, 1)
            break
          }
        }
      }
    },
    handleSelectAll(selection) {
      if (selection.length === 0) {
        for (let i = 0; i < this.store.data.length; ++i) {
          for (let j = 0; j < this.containerList.length; ++j) {
            if (this.store.data[i].roleId === this.containerList[j].roleId) {
              this.containerList.splice(j, 1)
              break
            }
          }
        }
      }
    },
    handleEmptySelectedList() {
      this.containerList = []
      this.selectedList = []
      this.$refs.searchInput.clear()
      this.$refs.table.clearSelection()
    },
    handleSelectionChange(val) {
      this.selectedList = val
      for (let i = 0; i < this.selectedList.length; ++i) {
        const flag = false
        for (let j = 0; j < this.containerList.length; ++j) {
          if (this.containerList[j].roleId === this.selectedList[i].roleId) {
            flag = true
            break
          }
        }
        !flag ? this.containerList.push(this.selectedList[i]) : ''
      }
    },
    handleReturnSelectedList() {
      return this.containerList
    },
    handleCheckCheckbox() {
      this.$nextTick(() => {
        for (let i = 0; i < this.containerList.length; ++i) {
          for (let j = 0; j < this.store.data.length; ++j) {
            if (this.containerList[i].roleId === this.store.data[j].roleId) {
              this.$refs.table.toggleRowSelection(this.store.data[j], true)
              break
            }
          }
        }
      })
    },
    handleInputClick(ev, val) {
      let params = {}
      params.q_roleName = val
      this.store._searchParams = params
      this.$refs.table.load(1, this.store.limit)
    },
    handleRoleDel(data) {
      for (let i = 0; i < this.store.data.length; ++i) {
        if (data.roleId === this.store.data[i].roleId) {
          this.$refs.table.toggleRowSelection(this.store.data[i], false)
          break
        }
      }
      for (let i = 0; i < this.containerList.length; ++i) {
        if (data.roleId === this.containerList[i].roleId) {
          this.containerList.splice(i, 1)
          break
        }
      }
    },
    // eslint-disable-next-line
    renderWrapTable(h) {
      return (
        <WrapTable
          ref='table'
          getData={this.getData}
          total={this.total}
          data={this.data}
          fields={this.columns}
          limitNum={this.limitNum}
          tooltip-effect='dark'
          border
          stripe
          paginationLayout='->, prev, pager, next'
          default-sort={{ prop: 'funId', order: 'descending' }}
          on-selection-change={this.handleSelectionChange}
          on-select={this.handleSelect}
          on-select-all={this.handleSelectAll}>
          <SearchForm
            items={this.searchFields}
            props-model={this.searchModel}
            slot='searchPanel'
            ref='searchForm'>
            <ButtonList
              operateBtnList={this.searchBtnList}
              props-model={this.searchModel}></ButtonList>
          </SearchForm>

          <c-row slot='toolPanel' class='toolPanel'>
            <ButtonList operateBtnList={this.toolPanelBtnList}></ButtonList>
          </c-row>
        </WrapTable>
      )
    },
    // eslint-disable-next-line
    renderSearch(h) {
      return (
        <c-input
          ref='searchInput'
          class='search-input'
          placeholder='输入角色名称搜索'
          on-input={event => {
            this.searchInput = event
          }}
          nativeOnKeydown={ev => {
            ev.keyCode === 13
              ? this.handleInputClick(ev, this.searchInput)
              : null
          }}>
          <i
            slot='suffix'
            class='el-input__icon el-icon-search'
            on-click={ev => this.handleInputClick(ev, this.searchInput)}></i>
        </c-input>
      )
    }
  },
  render(h) {
    return (
      <div v-show='pshow'>
        <c-row class='body-header'>
          <c-col span={this.spanLeftVal} class='title'>
            {this.currentUserKey}: {this.currentUserName}
          </c-col>
          <c-col span={this.spanRightVal}>{this.renderSearch(h)}</c-col>
        </c-row>
        <div class='user-top'>{this.renderWrapTable(h)}</div>
        <div class='user-bottom'>
          <ContainerList
            ref='containerList'
            title='已分配角色'
            equal={(a, b) => {
              return a.roleId === b.roleId
            }}
            formater={item => {
              return item.roleName
            }}
            value={this.containerList}
            on-deleteItem={this.handleRoleDel}></ContainerList>
        </div>
      </div>
    )
  }
}
</script>

<style lang="scss">
.body-header {
  display: flex;
  align-items: center;
  .search-input {
    width: 70%;
    float: right;
    .el-input__suffix {
      cursor: pointer;
      border-left: 1px solid #e6e6e6;
    }
  }
}
.user-top {
  height: 333px;
  box-sizing: border-box;
  .wrap-table {
    margin-top: 0;
    .searchPanel {
      display: none;
    }
    .pagination {
      margin: 5px 0;
      padding-right: 0;
    }
  }
}
.user-bottom {
  height: 112px;
}
</style>
